//
//  NowPlayingCenter.swift
//  MyVideo
//
//  Created by han on 2021/4/27.
//

import MediaPlayer
// 一个可用于设置并显示APP中当前播放的媒体信息的对象
/*
 1、在设备锁屏界面和控制中心中(in the multimedia controls in the multitasking UI)显示媒体信息
    2、通过AirPlay将媒体资源在AppleTV中播放时，播放信息将会出现在电视屏幕上。
    3、当前设备连接到一个iPod附件上，附件上也会显示当前正在播放的媒体信息
 */
class NowPlayingCenter {
    static func handleItemChange(item: PlaylistItem?, index: Int, count: Int) {
        
        let nowPlayingInfoCenter = MPNowPlayingInfoCenter.default()
        var nowPlayingInfo = [String: Any]()
        
        if let currentItem = item {
            
            nowPlayingInfo = nowPlayingInfoCenter.nowPlayingInfo ?? [String: Any]()
            
            nowPlayingInfo[MPNowPlayingInfoPropertyMediaType] = MPNowPlayingInfoMediaType.audio.rawValue
            nowPlayingInfo[MPNowPlayingInfoPropertyIsLiveStream] = false
            nowPlayingInfo[MPMediaItemPropertyTitle] = currentItem.title
            nowPlayingInfo[MPMediaItemPropertyArtist] = currentItem.artist
            
            nowPlayingInfo[MPNowPlayingInfoPropertyPlaybackQueueIndex] = index
            nowPlayingInfo[MPNowPlayingInfoPropertyPlaybackQueueCount] = count
            
            // Reinitialize information about the playback position.
            nowPlayingInfo[MPMediaItemPropertyPlaybackDuration] = nil
            nowPlayingInfo[MPNowPlayingInfoPropertyElapsedPlaybackTime] = nil
            nowPlayingInfo[MPNowPlayingInfoPropertyPlaybackRate] = nil
            nowPlayingInfo[MPNowPlayingInfoPropertyDefaultPlaybackRate] = nil
        }
        
        nowPlayingInfoCenter.nowPlayingInfo = nowPlayingInfo
    }
    
    static func handlePlaybackChange(playing: Bool, rate: Float, position: Double, duration: Double) {
        
        let nowPlayingInfoCenter = MPNowPlayingInfoCenter.default()
        var nowPlayingInfo = nowPlayingInfoCenter.nowPlayingInfo ?? [String: Any]()
        
        nowPlayingInfo[MPMediaItemPropertyPlaybackDuration] = Float(duration)
        nowPlayingInfo[MPNowPlayingInfoPropertyElapsedPlaybackTime] = Float(position)
        nowPlayingInfo[MPNowPlayingInfoPropertyPlaybackRate] = rate
        nowPlayingInfo[MPNowPlayingInfoPropertyDefaultPlaybackRate] = 1.0
        
        nowPlayingInfoCenter.nowPlayingInfo = nowPlayingInfo
    }
}
